package com.mc.code.web;


import com.mc.code.entity.CodeSkill;
import com.mc.code.entity.CodeUserId;
import com.mc.code.entity.CodeUsers;
import com.mc.code.entity.Skill;
import com.mc.code.service.LoginService;
import com.mc.code.service.UsersService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.thymeleaf.expression.Ids;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@Controller
@RequestMapping("logged")
public class loginController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private UsersService usersService;


    //登录账号
    @RequestMapping(value = "login", method = {RequestMethod.GET})
    public String login(HttpServletRequest request, Model model) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username + "," + password);
        List<CodeUsers> codeUsers = loginService.login(username);
        if (codeUsers != null)
            if (codeUsers.get(0).getPassword().equals(password)) {
                model.addAttribute("codeUsers", codeUsers);
                //登录成功后的首页
                return "loginIndex";
            }

        return "login";
    }

    //    登陆以后点logo或者首页带值回到首页
    @RequestMapping("loginIndex")
    public String loginIndex(HttpServletRequest request, Model model, String userNo) {
        System.out.println(userNo);
        List<CodeUsers> codeUsers = usersService.codeUsers(userNo);
        model.addAttribute("codeUsers", codeUsers);
        return "loginIndex";
    }

    //    注册账号
    @RequestMapping("enroll")
    public String enroll(HttpServletRequest request, Model model) {
        String nickName = request.getParameter("nickName");
        String username = request.getParameter("username");
        String psd = request.getParameter("password");
        int type = Integer.parseInt(request.getParameter("Type"));
        System.out.println("注册时所选的身份类型为:" + type);

        CodeUsers codeUsers = new CodeUsers();

        int userNo = loginService.maxUserNo() + 1;
        System.out.println(userNo);

        codeUsers.setUserNo(userNo);
        codeUsers.setNickName(nickName);
        codeUsers.setUsername(username);
        codeUsers.setPassword(psd);
        codeUsers.setType(type);
        loginService.registerUser(codeUsers);


        return "login";
    }


    //        个人中心
    @RequestMapping("userInformation")
    public String userInformation(HttpServletRequest request, Model model, String userNo) {
        System.out.println(userNo);
        List<CodeUsers> codeUsers = usersService.codeUsers(userNo);
        List<CodeUserId> codeUserIds = usersService.userId(userNo);
//    拉取所有技能方向
        List<CodeSkill> codeSkills = usersService.selectSkills();
        model.addAttribute("codeSkills", codeSkills);
//    拉取会的技能
        List<Skill> skills = usersService.selectGoodSkills(userNo);
        System.out.println(skills);
        model.addAttribute("skills", skills);
        model.addAttribute("codeUserID", codeUserIds);
        model.addAttribute("codeUsers", codeUsers);
        return "userInformation";
    }

    //        修改邮箱电话后个人中心
    @RequestMapping(value = "changeInformation", method = {RequestMethod.POST})
    public String changeInformation(HttpServletRequest request, Model model, String userNo) {
        System.out.println("用户编号" + userNo);
        String eamil = request.getParameter("email");
        String phoneNum = request.getParameter("phoneNum");
        CodeUsers codeUser = new CodeUsers();
        codeUser.setEmail(eamil);
        codeUser.setPhoneNum(phoneNum);
        codeUser.setUserNo(Integer.parseInt(userNo));
//    更新个人信息里的邮箱和手机号
        usersService.updateContact(codeUser);
        List<CodeUsers> codeUsers = usersService.codeUsers(userNo);
        model.addAttribute("codeUsers", codeUsers);
        List<CodeUserId> codeUserIds = usersService.userId(userNo);
//    拉取所有技能方向
        List<CodeSkill> codeSkills = usersService.selectSkills();
        model.addAttribute("codeSkills", codeSkills);
//    拉取会的技能
        List<Skill> skills = usersService.selectGoodSkills(userNo);
        System.out.println(skills);
        model.addAttribute("skills", skills);
        model.addAttribute("codeUserID", codeUserIds);
        return "userInformation";
    }

    //修改用户头像
    @RequestMapping(value = "userImage", method = {RequestMethod.POST})
    public String userImage(HttpServletRequest request, Model model, String userNo) throws IOException {
        System.out.println("修改头像" + userNo);
//    拉取所有技能方向
        List<CodeSkill> codeSkills = usersService.selectSkills();
        model.addAttribute("codeSkills", codeSkills);
//    拉取会的技能
        List<Skill> skills = usersService.selectGoodSkills(userNo);
        System.out.println(skills);
        model.addAttribute("skills", skills);
        //开始文件上传
        CodeUsers user = new CodeUsers();
        user.setUserNo(Integer.parseInt(userNo));
//        头像上传
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                String pa = "E:/inno/ideaIUWorkSpace/pic/";
                //一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                System.out.println(file.getOriginalFilename());
                if (file != null) {
                    String path = file.getOriginalFilename();
                    //找到.的下标
                    int begin = path.indexOf(".");
                    //找到字符串末位下标，即字符串长度
                    int last = path.length();
                    //反向找到第一个\
                    int xg = path.lastIndexOf("\\");
                    String str = null;
                    if (begin != -1) {
                        str = path.substring(begin);
                    }
                    System.out.println("判断文件是啥：" + str);
//                    图片格式有：BMP、JPG、JPEG、PNG、GIF。
                    if (str != null) {
                        if (str.equals(".jpg") || str.equals(".png")) {
                            String img = UUID.randomUUID() + path.substring(begin, last);
                            user.setImage(img);
                            String newPath = pa + img;
                            //上传
                            file.transferTo(new File(pa + img));
                        }

                    }
                }
            }

            //    插入数据库
            usersService.updateImage(user);
        }
        List<CodeUsers> codeUsers = usersService.codeUsers(userNo);
        System.out.println("个人中心" + codeUsers);
        List<CodeUserId> codeUserIds = usersService.userId(userNo);
        System.out.println(codeUserIds);
        model.addAttribute("codeUserID", codeUserIds);
        model.addAttribute("codeUsers", codeUsers);
        return "userInformation";
    }


    //       修改擅长方向后个人信息
    @RequestMapping(value = "changeSkills", method = {RequestMethod.GET})
    public String changeSkills(HttpServletRequest request, Model model) {
        String id = request.getParameter("ids");
        String[] sids = id.split(",");
        Skill skill = new Skill();
        String userNo = sids[sids.length-1];
        skill.setUserNum(Integer.parseInt(sids[sids.length - 1]));
        int i = 0;
        while (i< sids.length - 1) {
            switch (sids[i]) {
                case "1":
                    skill.setJava(1);i++;
                    break;
                case "2":
                    skill.setNet(1);i++;
                    break;
                case "3":
                    skill.setAsp(1);i++;
                    break;
                case "4":
                    skill.setC(1);i++;
                    break;
                case "5":
                    skill.setPhp(1);i++;
                    break;
                case "6":
                    skill.setBigdata(1);i++;
                    break;
                default:i++;
                    continue;
            }
        }
        usersService.delSkill(skill);
        usersService.insertSkill(skill);
        CodeUsers codeUser=new CodeUsers();
//    更新个人信息里的邮箱和手机号
        List<CodeUsers> codeUsers=usersService.codeUsers(userNo);
        model.addAttribute("codeUsers",codeUsers);
        List<CodeUserId> codeUserIds=usersService.userId(userNo);

//    拉取所有技能方向
        List<CodeSkill> codeSkills=usersService.selectSkills();
        model.addAttribute("codeSkills",codeSkills);
//    拉取会的技能
        List<Skill> skills=usersService.selectGoodSkills(userNo);
        System.out.println(skills);
        model.addAttribute("skills",skills);
        model.addAttribute("codeUserID",codeUserIds);
        return "userInformation";
    }



    //    账户余额
    @RequestMapping("moneyPay")
    public String moneyPay(HttpServletRequest request, Model model,String userNo){
      String banlance=request.getParameter("price");
      if(banlance !=null)
      {
          double charge = usersService.selectBanlance(userNo);
         charge+=Double.parseDouble(banlance);
          usersService.recharge(charge,userNo);
      }
      System.out.println(banlance);
        List<CodeUsers> codeUsers= usersService.codeUsers(userNo);
        model.addAttribute("codeUsers",codeUsers);
        return  "moneyPay";
    }

    //    账户支付密码 根据用户支付密码设置状态来验证跳转页面
    @RequestMapping("password")
    public String password(HttpServletRequest request, Model model, String userNo){
        int condition = usersService.selectPayCondition(userNo);
        List<CodeUsers> codeUsers= usersService.codeUsers(userNo);
        model.addAttribute("codeUsers",codeUsers);
        if(condition == 2){
            return "password2";
        }
        return  "password";
    }


    //    更新账户密码
    @RequestMapping("setPsd")
    public String setPsd(HttpServletRequest request, Model model,String userNo) {
        String psd=request.getParameter("password");
        usersService.updatePsd(userNo,psd);
        List<CodeUsers> codeUsers= usersService.codeUsers(userNo);
        model.addAttribute("codeUsers",codeUsers);
        return  "password";
    }




    //    用户建议
    @RequestMapping("advise")
public String advise(){
        return  null;
    }


}
